import Vue from 'vue'
import api from '@/plugins/axios/api'
import Router from 'vue-router'
import {ROUTER_DEFAULT_CONFIG} from '@/config/index'
import {clearLoginInfo} from '@/utils'
import {validURL} from '@/utils/validate'

Vue.use(Router)

const mImport = require('./import-' + process.env.NODE_ENV)
const globalRoutes = [
  {path: '/404', component: mImport('common/404'), name: '404', meta: {title: '404未找到'}},
  {path: '/401', component: mImport('common/401'), name: '401', meta: {title: '401权限不足'}},
  {path: '/login', component: mImport('common/login'), name: 'login', meta: {title: '登录'}},
  {path: '/gantt', component: mImport('common/gantt'), name: '甘特图', meta: {title: '甘特图'}},
  {path: '/redirect/:path*', component: mImport('redirect'), name: 'redirect'}
]
const mainRoutes = {
  path: '/',
  component: mImport('main/index.vue'),
  name: 'main',
  redirect: {name: 'home'},
  meta: {title: ''},
  children: [
    {path: '/home', component: mImport('common/home'), name: 'home', meta: {title: '首页'}}
  ],
  beforeEnter(to, from, next) {
    const token = Vue.cookie.get('token')
    if (!token || !/\S/.test(token)) {
      clearLoginInfo()
      return next({name: 'login'})
    }
    return next()
  }
}
const routerInstance = new Router({
  ...ROUTER_DEFAULT_CONFIG,
  isAddDynamicMenuRoutes: false,
  routes: [
    ...globalRoutes,
    mainRoutes
  ]
})

function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  let temp = []

  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      const route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      if (validURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
        route['meta']['title'] = menuList[i].name
      } else {
        try {
          route['component'] = mImport(`modules/${menuList[i].url}`) || null
          // eslint-disable-next-line no-empty
        } catch (e) {
        }
      }
      routes.push(route)
    }
  }
  let router = {
    path: '/contract-order-info-all',
    component: mImport('modules/contract/contract-order-info-all'),
    name: 'contractOrderInfoAll',
    meta: {
      menuId: '',
      title: '业务合同看板',
      isDynamic: true,
      isTab: true,
      iframeUrl: '',
    }
  }
  routes.push(router)
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    routerInstance.addRoutes([
      mainRoutes,
      {path: '*', redirect: {name: '404'}}
    ])
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRoutes.children || '[]'))
//    console.log('\n')
//    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
  //  console.log(mainRoutes.children)
///    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

function fnCurrentRouteType(route) {
  let temp = []

  for (let i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (globalRoutes[i].children && globalRoutes[i].children.length >= 1) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route) : 'login.vue.vue'
}

routerInstance.beforeEach((to, from, next) => {
  if (routerInstance.options.isAddDynamicMenuRoutes || fnCurrentRouteType(to) === 'global') {
    return next()
  }
  api['systemApi/menuNav']()
    .then(({data}) => {

      if (data && data.code === 0) {
        fnAddDynamicMenuRoutes(data.menuList)
        routerInstance.options.isAddDynamicMenuRoutes = true
        sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'))
        sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))
        return next({...to, replace: true})
      }
      sessionStorage.setItem('menuList', '[]')
      sessionStorage.setItem('permissions', '[]')
      return next()
    })
    .catch((e) => {
      console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
      routerInstance.push({name: 'login'})
    })
})

export default routerInstance
